package achi.community.irla.beans;

import achi.community.irla.database.AchievementsHandler;
import achi.community.irla.database.DatabaseImpl;
import achi.community.irla.database.ModelBean;
import achi.community.irla.entities.Achievements;
import achi.community.irla.entities.Achievements_completed;
import achi.community.irla.entities.Users;
import com.icesoft.faces.component.dragdrop.DndEvent;
import com.icesoft.faces.component.dragdrop.DragEvent;
import com.icesoft.faces.component.dragdrop.DropEvent;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.ejb.EJB;
import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIViewRoot;
import javax.faces.component.html.HtmlPanelGroup;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

/**
 * <p>The DragDropBean handles DragEvent listeners for the Drag and Drop
 * tutorial.</p>
 */
@ManagedBean
@RequestScoped
public class NewsControlBean implements Serializable {

    private boolean popup = false;
    private String style = "achi-box-out";
    private String dropPlace;
    //@ManagedProperty(value = "#{searchBackBean}")
    //SearchBackBean backingBean;
    private HashMap<String, Achievements> targets;
    private HashMap<String, Achievements_completed> completed;
    @ManagedProperty(value = "#{achievementsHandler}")
    AchievementsHandler achiHandler;
    @ManagedProperty(value = "#{modelBean}")
    ModelBean modelBean;

    /**
     * @ManagedProperty(value = "#{completedBackBean}") CompletedBackBean
     * completedBean;
     */
    public ModelBean getModelBean() {
        return modelBean;
    }

    public void setModelBean(ModelBean modelBean) {
        this.modelBean = modelBean;
    }

    public AchievementsHandler getAchiHandler() {
        return achiHandler;
    }

    public void setAchiHandler(AchievementsHandler achiHandler) {
        this.achiHandler = achiHandler;
    }

    public HashMap<String, Achievements> getTargets() {
        targets = achiHandler.getTargetMap();
        return targets;
    }

    public void setTest(HashMap<String, Achievements> targets) {
        this.targets = targets;
    }

    public HashMap<String, Achievements_completed> getCompleted() {
        completed = achiHandler.getCompletedMap();
        /**
        //private HashMap<String, Achievements_completed> completed;
        Collection c = completed.values();
        Iterator itr = c.iterator();
        boolean error = false;
        while (itr.hasNext()) {
            Achievements_completed achi = (Achievements_completed) itr.next();
            if (achi.getAchievement() == null) {
                error = true;
            }
        }
*/
        if (true) {
            return completed;
        } else {
            return null;
        }
    }

    public void setCompleted(HashMap<String, Achievements_completed> completed) {
        this.completed = completed;
    }

    public void targetMovedListener(DragEvent dragEvent) {

        System.out.println("targetMoved:1");

        if (dragEvent.getEventType() == DndEvent.DROPPED) {

            System.out.println("targetMoved:2");

            dropPlace = (String) dragEvent.getTargetDropValue();
            HashMap<String, Achievements> targetMap = achiHandler.getTargetMap();

            HashMap<String, Achievements_completed> completedMap = achiHandler.getCompletedMap();
            Achievements draggedAchi = (Achievements) dragEvent.getTargetDragValue();
            Achievements droppedAchi = targetMap.get(dropPlace);

            System.out.println("targetMoved:3");
            String draggedKey = "";
            Iterator it = targetMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pairs = (Map.Entry) it.next();
                Achievements achi = (Achievements) pairs.getValue();
                if (achi.equals(draggedAchi)) {
                    draggedKey = (String) pairs.getKey();
                }
            }
            System.out.println("targetMoved:4");
            if (!draggedKey.equals("")) {
                if (dropPlace.startsWith("d")) {
                    System.out.println("targetMoved:5");
                    Achievements emptyAchi = modelBean.getAchievement("Empty");
                    targetMap.put(draggedKey, emptyAchi);

                    Achievements_completed achiCompleted = completedMap.get(dropPlace);
                    Achievements_completed comp = newCompleted(achiCompleted, draggedAchi);

//                    Achievements_completed achiCompleted = createCompleted(draggedAchi, dropPlace);
                    completedMap.put(dropPlace, comp); // OM DEN INTE REDAN FINNS!?
                    modelBean.updateTarget(draggedKey, emptyAchi);
                    System.out.println("innan");
                    modelBean.updateCompleted(comp);
                    System.out.println("efter");
                } else {
                    targetMap.put(draggedKey, droppedAchi);
                    targetMap.put(dropPlace, draggedAchi);
                    modelBean.updateTarget(draggedKey, droppedAchi);
                    modelBean.updateTarget(dropPlace, draggedAchi);

                    //  System.out.println("dragedKey:"+draggedKey+" droppedAchi:"+droppedAchi);
                    // System.out.println("dropPlace:"+dropPlace+" draggedAchi:"+draggedAchi+"\n");
                }
            }
        } else if (dragEvent.getEventType() == DndEvent.HOVER_START) {
            String clientId = dragEvent.getTargetClientId();
            int end = clientId.length();
            String id = clientId.substring(end - 3, end);
            System.out.println("id:" + id);
            FacesContext context = FacesContext.getCurrentInstance();



            //HtmlPanelGroup panel = (HtmlPanelGroup) context.getApplication()..getApplication().createComponent(
            //  HtmlPanelGroup.COMPONENT_TYPE);
            //HtmlPanelGroup panela;
            //panela.setStyle("background: green");
            //IcePanelGroup ice;




            // TODO...(effekt innan man släpper)
        }
        // System.out.println(dragEvent.getEventType());
        //  System.out.println("aaaaaaaaaaaaa");

    }

    /**
     * public void targetMovedListener(DropEvent dragEvent) { if
     * (dragEvent.getEventType() == DndEvent.DROPPED) { dropPlace = (String)
     * dragEvent.getTargetDropValue(); HashMap<String, Achievements> targetMap =
     * achiHandler.getTargetMap(); HashMap<String, Achievements> completedMap =
     * achiHandler.getCompletedMap(); Achievements draggedAchi = (Achievements)
     * dragEvent.getTargetDragValue(); Achievements droppedAchi =
     * targetMap.get(dropPlace);
     *
     * String draggedKey = ""; Iterator it = targetMap.entrySet().iterator();
     * while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next();
     * Achievements achi = (Achievements) pairs.getValue(); if
     * (achi.equals(draggedAchi)) { draggedKey = (String) pairs.getKey(); } } if
     * (!draggedKey.equals("")) { if (dropPlace.startsWith("d")) { Achievements
     * emptyAchi = modelBean.getAchievement("Empty"); targetMap.put(draggedKey,
     * emptyAchi); completedMap.put(dropPlace, draggedAchi); // OM DEN INTE
     * REDAN FINNS!? modelBean.updateTarget(draggedKey, emptyAchi);
     * modelBean.updateCompleted(dropPlace, emptyAchi); } else {
     * targetMap.put(draggedKey, droppedAchi); targetMap.put(dropPlace,
     * draggedAchi); modelBean.updateTarget(draggedKey,droppedAchi);
     * modelBean.updateTarget(dropPlace, draggedAchi);
     *
     * // System.out.println("dragedKey:"+draggedKey+"
     * droppedAchi:"+droppedAchi); //
     * System.out.println("dropPlace:"+dropPlace+"
     * draggedAchi:"+draggedAchi+"\n"); } } } else if (dragEvent.getEventType()
     * == DndEvent.HOVER_START) { //dropPlace = (String)
     * dragEvent.getTargetDropValue(); System.out.println("INNAN");
     * System.out.println(dragEvent.getTargetClientId()); //
     * System.out.println(dragEvent.getComponent());
     * System.out.println("EFTER"); // TODO...(effekt innan man släpper) }
     * //System.out.println(dragEvent.getEventType()); }
     *
     */
    public void completeMovedListener(DragEvent dragEvent) {
        System.out.println("completedMovedListenet()");

        if (dragEvent.getEventType() == DndEvent.DROPPED) {
            System.out.println("completeMovedListener()");

            dropPlace = (String) dragEvent.getTargetDropValue();
            HashMap<String, Achievements> targetMap = achiHandler.getTargetMap();
            HashMap<String, Achievements_completed> completedMap = achiHandler.getCompletedMap();
            Achievements_completed draggedAchi = (Achievements_completed) dragEvent.getTargetDragValue();
            Achievements_completed droppedAchi = completedMap.get(dropPlace);

            String draggedKey = "";
            Iterator it = completedMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pairs = (Map.Entry) it.next();
                Achievements_completed cAchi = (Achievements_completed) pairs.getValue();
                if (cAchi.equals(draggedAchi)) {
                    draggedKey = (String) pairs.getKey();
                }
            }

            if (!draggedKey.equals("")) {
                if (dropPlace.startsWith("t")) {
                    // Achievements emptyAchi = modelBean.getAchievement("Empty");

                    targetMap.put(dropPlace, draggedAchi.getAchievement()); // OM DEN INTE REDAN FINNS!?
                    modelBean.updateTarget(dropPlace, draggedAchi.getAchievement());

                    draggedAchi = cleanCompleted(draggedAchi);
                    //draggedAchi.setAchievement(emptyAchi);
                    completedMap.put(draggedKey, draggedAchi);
                    modelBean.updateCompleted(draggedAchi);

                } else {
                    //  System.out.println("dragedKey:"+draggedKey+" droppedAchi:"+droppedAchi);
                    //    System.out.println("dropPlace:"+dropPlace+" draggedAchi:"+draggedAchi+"\n");
                    if (!draggedKey.equals(dropPlace)) {
                        droppedAchi.setPos(draggedKey);
                        completedMap.put(draggedKey, droppedAchi);
                        modelBean.updateCompleted(droppedAchi);

                        draggedAchi.setPos(dropPlace);
                        completedMap.put(dropPlace, draggedAchi);
                        modelBean.updateCompleted(draggedAchi);
                    }
                }
            }

        } else if (dragEvent.getEventType() == DndEvent.HOVER_START) {
            style = "achi-box-out-active";
        }

    }

    public Achievements_completed cleanCompleted(Achievements_completed achi) {
        Achievements emptyAchi = modelBean.getAchievement("Empty");
        achi.setAchievement(emptyAchi);
        achi.setDescription(null);
        achi.setImages(null);
        achi.setDate_completed(null);
        return achi;
    }

    public Achievements_completed newCompleted(Achievements_completed c, Achievements a) {
        c.setAchievement(a);

        Date d = new Date();
        SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = dateformatter.format(d.getTime());
        c.setDate_completed(strDate);

        c.setImages(null);
        c.setDescription(null);
        /**
         * Achievements_completed a = new Achievements_completed();
         * a.setDate_completed((new Date()).toString()); a.setAchievement(achi);
         * a.setPos(dropPlace); Users u = modelBean.getUser(); a.setUser(u);
         *
         */
        return c;
    }

    public void dragListener(DragEvent dragEvent) {

        if (dragEvent.getEventType() == DndEvent.DROPPED) {
            System.out.println("dragListener()");

            Achievements achi = (Achievements) dragEvent.getTargetDragValue();
            HashMap<String, Achievements> targetMap = achiHandler.getTargetMap();
            HashMap<String, Achievements_completed> completedMap = achiHandler.getCompletedMap();
            dropPlace = (String) dragEvent.getTargetDropValue();
            System.out.println("2");
            Collection<Achievements> achiCol = new LinkedList<Achievements>();

            if (dropPlace.startsWith("t")) {
                achiCol = targetMap.values();
            } else {
                Collection<Achievements_completed> completedCol = completedMap.values();
                for (Achievements_completed ac : completedCol) {
                    achiCol.add(ac.getAchievement());
                }
            }
            System.out.println("3");

            // Leta efter dubletter
            boolean found = false;
            Long id = achi.getId();
            for (Achievements ac : achiCol) {
                System.out.println(ac.getId());
                if ((ac.getId()).equals(id)) {
                    found = true;
                }
            }
            System.out.println("4");
            if (!found) {
                if (dropPlace.startsWith("t")) {
                    System.out.println("5");
                    modelBean.updateTarget(dropPlace, achi);
                    targetMap.put(dropPlace, achi);
                } else {
                    System.out.println("6");
                    Achievements_completed achiCompleted = completedMap.get(dropPlace);
                    Achievements_completed comp = newCompleted(achiCompleted, achi);
                    //achiCompleted.setDate_completed((new Date()).toString());
                    //achiCompleted.setAchievement(achi);

                    //Achievements_completed comp = createCompleted(achi, dropPlace);
                    modelBean.updateCompleted(comp);
                    completedMap.put(dropPlace, comp);
                    System.out.println("7");
                }
                // }
            }
        } else if (dragEvent.getEventType() == DndEvent.HOVER_START) {
            System.out.println("HOVER START!");
            // TODO...(effekt innan man släpper)
        }

    }

    /**
     * public String redirectComplete() {// throws IOException{
     *
     * FacesContext context = FacesContext.getCurrentInstance(); Map requestMap
     * = context.getExternalContext().getRequestParameterMap(); String cId =
     * (String) requestMap.get("id"); System.out.println("value::" + cId);
     *
     * fillCompleteBean(cId);
     * //FacesContext.getCurrentInstance().getExternalContext().redirect("completed.jsf");
     *
     * return "completed?faces-redirect=true"; }
    *
     */
    /**
     * public void fillCompleteBean(String cId){ Achievements_completed cAchi =
     * modelBean.getAchiCompleted(cId); completedBean.setUser(cAchi.getUser());
     * completedBean.setDate_completed(cAchi.getDate_completed());
     * completedBean.setDescription(cAchi.getDescription());
     * completedBean.setAchievement(cAchi.getAchievement());
     * completedBean.setImages(cAchi.getImages()); }
     */
    public String getDropValue() {
        return dropPlace;
    }

    public boolean isPopup() {
        return popup;
    }

    public void setPopup(boolean popup) {
        this.popup = popup;
    }

    public void closePopup(ActionEvent event) {
        System.out.println("CLOSE!!!");
        popup = false;
    }

    public void openPopup(ActionEvent event) {
        popup = true;
    }

    public String getStyle() {
        return style;
    }

    public void setStyle(String style) {
        this.style = style;
    }
}
